/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tlf.dyjc5.servlet.system;

import com.tlf.dyjc5.bo.UserBean;
import com.tlf.dyjc5.service.UserService;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.dusin.commonutil.CipherUtil;
import org.dusin.web.util.CommonWebUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author Administrator
 */
public class LoginServlet extends HttpServlet {

    private UserBean UserBean = null;
    private int maxTriesBeforeLock = 6;// 登陆最大尝试次数

    @Override
    public void init() throws ServletException {
        super.init(); //To change body of generated methods, choose Tools | Templates.
        try {
            maxTriesBeforeLock = Integer.parseInt(this.getInitParameter("wrongLoginTimes"));
        } catch (Exception e) {
            maxTriesBeforeLock = 6;
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession session = request.getSession(true);

            ServletContext servletContext = getServletContext();
            Map vipList = (Map) session.getServletContext().getAttribute("vipList");
            Map userList = (Map) session.getServletContext().getAttribute("userList");
            int maxSession = CommonWebUtil.getIntParameter(servletContext.getInitParameter("maxSession"), 100);
            int currentSessionCounter = vipList.size() + userList.size();   //当前已登陆的会话数目


            String account = request.getParameter("pa11");
            String pass = request.getParameter("pa22");
            account = CipherUtil.decode(account);
            pass  = CipherUtil.decode(pass);
            //String account = "super";     //用于调试
            //String pass="8";
            String usercheckString = request.getParameter("savename");
            String passchkeckString = request.getParameter("savepass");
            if (usercheckString == null) {
                Cookie c1 = new Cookie("username", "undefined");
                c1.setHttpOnly(true);
                c1.setSecure(true);
                response.addCookie(c1);
            } else {
                Cookie c1 = new Cookie("username", account);
                c1.setHttpOnly(true);
                c1.setSecure(true);
                response.addCookie(c1);
            }
            if (passchkeckString == null) {
                Cookie c2 = new Cookie("password", "undefined");
                c2.setHttpOnly(true);
                c2.setSecure(true);
                response.addCookie(c2);
            } else {
                Cookie c2 = new Cookie("password", pass);
                c2.setHttpOnly(true);
                c2.setSecure(true);
                response.addCookie(c2);
            }
            String checkcodetext = request.getParameter("checkcodetext").toUpperCase();

            String randString;
            try {
                randString = ((String) session.getAttribute("rand")).toUpperCase();
            } catch (Exception e) {
                request.setAttribute("information", "校验码已过期");
                return;
            }
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            UserService userService = (UserService) context.getBean("userService");

            //if (checkcodetext.equals(randString)) {                
            if(true) { //跳过校验码
                String clientIP = request.getRemoteAddr();

                UserBean = userService.login(account, pass, clientIP);   //通过校验码后再验证密码
                if (UserBean != null) {
                    int sessionCount = vipList.size() + userList.size();

                    if(UserBean.getStatus()%10==9){
                        request.setAttribute("information", "账户被锁定,请与管理员联系!");
                        return;
                    }                    
                    if (UserBean.getWrongLoginTimes() >= maxTriesBeforeLock) {
                        if (!UserBean.isLocked()) {
                            userService.lock(String.valueOf(UserBean.getId()));
                        }
                        request.setAttribute("information", "已连续输入" + maxTriesBeforeLock + "次以上错误密码，账户被锁定。请与管理员联系");
                        return;
                    }
                    if(UserBean.getLoginStatus()==1){  //密码过期
                        request.setAttribute("information", "密码已过期，请与管理员联系");
                        return;
                    }else if (!UserBean.isIsLoginOk()) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("已连续输入").append(UserBean.getWrongLoginTimes()).append("次错误密码。\\n").append("如果连续输入").append(maxTriesBeforeLock).append("次错误密码，账户将被锁定");
                        request.setAttribute("information", sb.toString());
                        return;
                    }

                    //查找该用户是否已经登陆
                    //HttpSession oldSession =(HttpSession) session.getServletContext().getAttribute(account);
                    HttpSession oldSession = (HttpSession) userList.get(account);
                    if (oldSession == null) {
                        oldSession = (HttpSession) vipList.get(account);
                    }
                    if (oldSession != null&&oldSession!=session) {   //该用户已经登陆，踢出前一个登陆用户,oldSession不是当前的session
                        //String user = (String) oldSession.getAttribute("user");
                        //vipList.remove(user);
                        //userList.remove(user);
                        oldSession.invalidate();
                        //request.setAttribute("information", "该用户已在其它地方登陆");
                    }

                    if ((currentSessionCounter >= maxSession) && UserBean.getPriority() == 0) {
                        request.setAttribute("information", "对不起！系统忙，请稍候再试");
                        return;
                    }
                    if ((currentSessionCounter >= maxSession) && UserBean.getPriority() == 1) {
                        if (userList.size() > 0) {    //随机踢出一个普通用户
                            Object[] userNameArray = userList.keySet().toArray();
                            int kickOffNo = (int) (Math.random() * userNameArray.length);
                            HttpSession kickOffSession = (HttpSession) userList.remove(userNameArray[kickOffNo]);
                            kickOffSession.invalidate();
                        } else {
                            request.setAttribute("information", "对不起！系统忙，请稍候再试");
                            return;
                        }
                    }
                    //session.getServletContext().setAttribute(account, session);  //禁止一个用户同一时间同时登陆 ，设置

                    if (UserBean.getPriority() == 1) {
                        vipList.put(account, session);
                    } else {
                        userList.put(account, session);
                    }

                    session.setAttribute("currentOrgCode", UserBean.getOrgCode());
                    session.setAttribute("currentOrgName", UserBean.getOrgName());

                    session.setAttribute("realName", UserBean.getRealName());
                    session.setAttribute("orgCode", UserBean.getOrgCode()); //登录用户所属机构
                    //session.setAttribute("code", "01");//登录用户公司编码
                    session.setAttribute("companyName", UserBean.getOrgName());
                    session.setAttribute("user", UserBean.getLoginName());//登录用户名
                    session.setAttribute("userId", UserBean.getId());
                    session.setAttribute("userName", UserBean.getRealName());
                    session.setAttribute("IP", request.getRemoteAddr());
                    if (UserBean.getLoginName().equals("super")) {
                        session.setAttribute("currentOrgName", "超级用户");
                        session.setAttribute("companyName", "超级用户");
                    }
                    if (UserBean.getPriority() == 1) {   //vip用户
                        vipList.put(account, session);
                    } else {
                        userList.put(account, session);
                    }

                } else {
                    request.setAttribute("information", "该用户名不存在");
                }

            } else {
                request.setAttribute("information", "校验码错误");
            }

        } catch (org.springframework.dao.EmptyResultDataAccessException e) {
            request.setAttribute("information", "用户名不存在");
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            errorMessage = errorMessage.replaceAll("['\"]", "");
            request.setAttribute("information", "内部错误，登录失败");
            e.printStackTrace();
        } finally {
            RequestDispatcher dispatcher = request.getRequestDispatcher("LoginJP.jsp");
            dispatcher.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method. 不响应get请求
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
